#include <stdio.h>
#include <string.h>
#include "kfifo.h"
#include "main.h"	
#include "msg.h"



#define APP_MSG_BUFFER_LEN  4096

struct kfifo app_msg_kfifo = {0};
uint8_t app_msg_buffer[APP_MSG_BUFFER_LEN] = {0};


void app_msg_init(void)
{
    kfifo_init(&app_msg_kfifo, app_msg_buffer, APP_MSG_BUFFER_LEN);
}


/*__INLINE */void app_msg_send(uint8_t msg)
{
	uint8_t send[3];
	
	send[0] = MSG_TYPE_SYS;
	send[1] = msg;
	send[2] = 0;
	
    __kfifo_put(&app_msg_kfifo, send, 3);
}

void app_msg_send_with_param(uint8_t msg, uint8_t *param, uint8_t param_len)
{
	uint8_t send[32];
	
	send[0] = MSG_TYPE_SYS;
	send[1] = msg;
	send[2] = param_len;
	if(param_len > 0)
		memcpy(&send[3], (const uint8_t*)param, param_len);
	
    __kfifo_put(&app_msg_kfifo, send, param_len+3);
}

void app_msg_send_uart_data(uint8_t msg, uint8_t *param, uint8_t param_len)
{
	uint8_t send[32];
	
	send[0] = MSG_TYPE_UART;
	send[1] = msg;
	send[2] = param_len;
	if(param_len > 0)
		memcpy(&send[3], (const uint8_t*)param, param_len);
	
    __kfifo_put(&app_msg_kfifo, send, param_len+3);
}

/*__INLINE */uint8_t app_msg_get(uint8_t *msg_id, uint8_t *param, uint8_t *param_len)
{
    uint8_t msg_type, msg_len;
	uint8_t buf[32], len;
	
    len = __kfifo_get(&app_msg_kfifo, buf, 3);
	if(len > 2)
    {
		msg_type = buf[0];
		*msg_id = buf[1];
		msg_len = buf[2];
		if(msg_len > 0)
		{
			len = __kfifo_get(&app_msg_kfifo, buf, msg_len);
			if(len == msg_len)
			{
				memcpy(param, buf, len);
				*param_len = len;
			}
			else
				*param_len = 0;
			return msg_type;
		}
		else
		{
			*param_len = 0;
			return msg_type;
		}
	}
	else
    {
		return MSG_TYPE_NULL;
	}
}


